// pages/get_ticket/index.js
import { getUserOrder,cancel,orderpay,queryOrder,refund } from '../../api/order'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showToastState:true,//是否已加载全部
    navIndex:0,
    pageNum:1,//当前页
    pageSize:10,//当前页显示的条数
    // lists:[{title:"全部",data:[]},{title: "审核中",data: []},{title: "待参加",data: []},{title: "已结束",data: []},{title: "退款",data:[]}],
    lists:[{title:"全部",data:[]},{title: "审核中",data: []},{title: "待参加",data: []},{title: "已结束",data: []}],
    isRequest: false,
    loading: false, //上拉加载更多的loading
    refreshLoading: false //下拉刷新页面的loading
  },
  onShow() {
    this.feach()
  },
  feach() { //刷新
    this.setData({ pageNum: 1})
    this.getData(this.data.navIndex)
  },
  getData(typeIndex) { // 获取数据前的设置
    this.setData({ isRequest: false, showToastState: true })
    //不传查全部 订单状态：1=退款；2=取消；3=已结束；4=进行中；5=待参加；6=待支付
    switch (Number(typeIndex)) {
      case 0:
        this._getUserOrder();
        break;
      case 1:
        this._getUserOrder(5, 2)
        break;
      case 2:
        this._getUserOrder(5, 1)
        break;
      case 3:
        this._getUserOrder(3, 1)
        break;
    }
  },
  initList() { // 下拉刷新
    this.setData({refreshLoading: true})
    this.feach()
  },
  //获取更多数据
  loadMore(e){
    this.getData(e.currentTarget.dataset.index)
  },
  //获取订单列表
  _getUserOrder(state,isChecked){
    let { pageNum, pageSize, lists, isRequest, navIndex, scrollTop } = this.data
    if (!isRequest){
      this.setData({ isRequest: true })
      let obj = {
        pageNum: pageNum,
        pageSize: pageSize
      }
      if(state){ obj.orderStatus=state }
      if(isChecked){ obj.isChecked=isChecked }
      if(this.data.showToastState){
      getUserOrder(obj).then(res => {
        this.setData({ ['lists[' + navIndex + '].data']: res.rows.length > 0 ? [...(pageNum == 1 ? [] : lists[navIndex].data), ...res.rows] : (pageNum == 1 ? [] : lists), refreshLoading: false, 
        isRequest: false, showToastState: res.rows.length > 0 ? this.data.lists[navIndex].data.length > res.total : true})
        //小程序滚动到顶部
        wx.pageScrollTo({ scrollTop: 20 })
        if (res.rows.length > 0) {
          this.setData({ pageNum: Number(pageNum) + 1 })
        }
      })
    }
    }
  },
  getNavIndex(e){ // 点击切换
    this.setData({navIndex: e.currentTarget.dataset.index})
  },
  bindChange(e) { // swiper切换
    let current = e.detail.current
    this.setData({navIndex:current,pageNum: 1})
    this.getData(current)
  },
  //退款
  toRefund(e) {
    let that = this
    let {orderid,type}=e.currentTarget.dataset
    if(type==1){ //单体
      wx.navigateTo({
        url: '/pages/order-refund/index?orderid=' + orderid,
      })
    }else{//团队
      wx.navigateTo({
        url: '/pages/order-refund/index?orderid=' + orderid,
      })
    // let obj={
    //   orderId:orderid,
    //   refundRemark:''//退款说明
    // }
    // wx.showModal({
    //   content: '是否取消订单？',
    //   success (res) {
    //     if (res.confirm) {
    //         refund(obj).then(res=>{
    //           wx.showModal({
    //             title: '',
    //             content: '申请中',
    //             showCancel: false,//是否显示取消按钮
    //             confirmText: "确定",//默认是“确定”
    //             confirmColor: '#000000',//确定文字的颜色
    //             success: function (res) {
    //               wx.startPullDownRefresh()
    //               that.feach()
    //             }
    //           })
    //         })
    //     } else if (res.cancel) {
    //       console.log('用户点击取消')
    //     }
    //   }
    // })
    }
  },
  //取消订单
  toCancel(e){
    let that = this
    wx.showModal({
      content: '是否删除订单？',
      success (res) {
        if (res.confirm) {

          cancel(e.currentTarget.dataset.orderid).then(res => {
            if(res.code==0){
              wx.showToast({
                title: res.msg,
                icon:'success'
              })
            }else{
              wx.showToast({
                title: res.msg,
                icon:'none'
              })
            }
            setTimeout(function () {
             that.feach()
            }, 2000) 
          })
        } else if (res.cancel) {
        }
      }
    })
  },
  //去支付
  toPay(e){
  //调起官方微信支付接口
    orderpay(e.currentTarget.dataset.ordersn).then(res=>{
      if(res.data.needPay){
        this.Payment(res.data.result,e.currentTarget.dataset.ordersn)
      }else{
          //主动查询订单支付状态（第四步）
          this._queryOrder(e.currentTarget.dataset.ordersn)
      }
    })
  },
  
  //调起官方微信支付接口
  Payment(result,orderSn){
    let that = this
    wx.requestPayment({
      timeStamp: result.timeStamp,
      nonceStr: result.nonceStr,
      package: result.packageValue,
      signType: result.signType,
      paySign:  result.paySign,
      success (res) { 
          //主动查询订单支付状态（第四步）
          that._queryOrder(orderSn)
      },
      fail (res) { 
      }
    })
  },
     //主动查询订单支付状态（第四步）
     _queryOrder(orderSn){
       let  that = this
      queryOrder(orderSn).then(res=>{
        if(res.data.msg=="OK"){
          that.feach()
        }
    })
    },
  //查看详情
  toDetail(e) {
    wx.navigateTo({
      url: '/pages/order-new-detail/index?orderid=' + e.currentTarget.dataset.orderid,
    })
  },
  //取消订单
  refund(){
    wx.navigateTo({
      url: '/pages/order-refund/index',
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
  ,
  onUnload: function () {
    //如果是订单列表进来，正常返回，如果是下单流程进入订单详情，则返回到详情页面
    var pages = getCurrentPages();//页面指针数组
    var prepage = pages[pages.length - 2];//上一页面指针
    console.log(prepage.route)
    if (prepage.route == "pages/order/index") {

    }else if (prepage.route == "pages/competition_detail/index"){
    
    } else {
      wx.navigateBack({
        delta: 2
      })
    }
  }
})